import { Component, Injector, OnInit, ViewChild } from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { OrderService } from '../../../service/order/order.service';
import {
  SimpleTableComponent,
  SimpleTableColumn,
} from '@delon/abc/src/simple-table';
import { CommService } from '../../../service/comm/comm.service';
import { Constant, ServiceResult } from '@core/constant';
import { formatDate } from '@angular/common';
import { Router } from '@angular/router';
import { EmitterService } from 'app/service/emit.service';
import { NzModalService } from 'ng-zorro-antd';
import { UserSelectModalComponent } from '@shared/component/users/user-select-modal.component';
import { Timeout } from '@shared/descriptor/timeout';
import { saveAs } from 'file-saver';

@Component({
  selector: 'client-order-list',
  templateUrl: './client-order-list.component.html',
})
export class ClientOrderListComponent implements OnInit {
  get cnt(): Constant {
    return this.injector.get(Constant);
  }
  dateFormat = 'yyyy/MM/dd';
  ps = 10;
  q: any = {
    mode: 'other',
    orderId: '',
    zname: this.setting.user.name,
    orderStatus: 'unfinished',
  };
  znames = [];
  url = this.orderServ.list();
  data = [];
  checkedList = [];
  loading = false;
  isManager = false;
  statuss = [
    { text: 'Pending', value: 'NOCHECK' },
    { text: 'Confirmed', value: 'CHECKED' },
    { text: 'Shipping', value: 'SENDING' },
    { text: 'Complete', value: 'COMPLETE' },
    { text: 'Canceled', value: 'CANCEL' },
  ];

  @ViewChild('st') st: SimpleTableComponent;
  columns: SimpleTableColumn[] = [];

  constructor(
    private orderServ: OrderService,
    private injector: Injector,
    private comm: CommService,
    private http: _HttpClient,
    private setting: SettingsService,
    private emit: EmitterService,
    private router: Router,
    private modalService: NzModalService,
  ) {}

  ngOnInit() {
    this.buildColumn();
    this.emit.getMessage().subscribe(data => {
      if (data.text === 'RELOAD_ORDERS_LIST') {
        this.st.reload(this.q);
      }
    });
    this.loadZnames();
    this.checkUserIsManager();
  }

  @Timeout(500)
  checkUserIsManager() {
    if (this.setting.user.isManager) {
      this.isManager = true;
    } else {
      this.isManager = false;
    }
  }

  checkboxChange(list: any[]) {
    this.checkedList = list;
  }
  loadZnames() {
    this.znames = [];
    this.orderServ.getZnames().subscribe(data => {
      const ret: ServiceResult = <ServiceResult>data;
      if (ret.status === 200) {
        this.znames.push({
          text: '当前用户',
          value: this.setting.user.username,
        });
        this.znames.push({
          text: '全部负责人',
          value: '',
        });
        for (const row of ret['data']['rows']) {
          if (row) {
            this.znames.push({
              text: row,
              value: row,
            });
          }
        }
      }
    });
  }

  buildColumn() {
    this.columns = [
      { title: '', index: 'key', type: 'checkbox' },
      { title: '单号', index: 'orderId', i18n: 'orderId' },
      { title: '提交日期', index: 'createDate', i18n: 'createDate' },
      { title: '客户', index: 'clientName', i18n: 'user', render: 'clientName' },
      { title: '负责人', index: 'zname', i18n: 'zname' },
      { title: '数量', index: 'qty', i18n: 'qty' },
      { title: '金额', index: 'price', i18n: 'price' },
      {
        title: '状态',
        index: 'status',
        type: 'badge',
        i18n: 'status',
        filters: this.statuss,
        filterMultiple: false,
        filter: () => true,
        filterConfirmText: 'Ok',
        filterClearText: 'Reset',
        badge: {
          NOCHECK: { text: 'Pending', color: 'processing' },
          CHECKED: { text: 'Confirmed', color: 'warning' },
          SENDING: { text: 'Shipping', color: 'warning' },
          COMPLETE: { text: 'Complete', color: 'success' },
          CANCEL: { text: 'Canceled', color: 'error' },
        },
      },
      {
        title: '',
        buttons: [
          {
            text: '明细',
            i18n: 'view',
            type: 'link',
            click: (record: any) =>
              this.router.navigate(['/order/clientorder/view/' + record.id]),
          },
        ],
      },
    ];
  }

  dateChange(result: Date[]): void {
    if (result.length !== 0) {
      this.q.startDate = formatDate(result[0], 'yyyy-MM-dd', 'en-US');
      this.q.endDate = formatDate(result[1], 'yyyy-MM-dd', 'en-US');
    } else {
      this.q.startDate = '';
      this.q.endDate = '';
    }
  }

  showUserSelect() {
    let level = 'FIRST';
    if (this.setting.user.isManager) {
      level = 'FIRST';
    } else if (this.setting.user.level === 'FIRST') {
      level = 'SECOND';
    } else if (this.setting.user.level === 'SECOND') {
      level = 'THIRD';
    }
    const modal = this.modalService.create({
      nzContent: UserSelectModalComponent,
      nzWidth: '730px',
      nzComponentParams: { selectLevel: level, lockLevel: true, multi: false },
      nzFooter: null,
    });
    modal.afterOpen.subscribe(() => {
      modal
        .getContentComponent()
        .getSubject()
        .subscribe(data => {
          const users = data as Array<any>;
          if (users && users.length !== 0) {
            this.q.username = users[0].username;
          }
        });
    });
  }
  export() {
    this.orderServ.exportOrderDetail(
      this.q.mode,
      this.q.orderId,
      this.q.orderStatus,
      this.q.zname,
      this.q.startDate,
      this.q.endDate,
    );
  }
}
